<template>
  <el-dialog
    title="资金需求测算"
    width="800px"
    top="8vh"
    append-to-body
    :close-on-click-modal="false"
    :visible.sync="visible"
    :before-close="beforeClose"
  >
    <div
      class="calc-panel"
      style="width: 600px; margin: 0 auto"
      v-loading="loading"
      :class="calcStep === 1 ? 'show-result' : ''"
      @keyup.enter="handleClac"
    >
      <div class="d-flex">
        <div class="flex-1">
          <div class="d-flex">
            <div style="min-width: 40px; line-height: 36px" class="text-muted">规模</div>
            <el-input class="mb-1" type="number" v-model.number="scale" placeholder="请输入规模">
              <div slot="append" class="text-center" style="min-width: 40px">{{ scaleUnit }}</div>
            </el-input>
          </div>
          <div class="d-flex">
            <div style="min-width: 40px; line-height: 36px" class="text-muted">负债</div>
            <el-input
              type="number"
              v-model.number="liabilities"
              placeholder="请输入负债（不填视为0）"
            >
              <div slot="append" class="text-center" style="min-width: 40px">万元</div>
            </el-input>
          </div>
        </div>
        <el-button type="primary" class="btn-long ml-1" @click="handleClac">测算</el-button>
      </div>

      <div v-show="calcStep === 1">
        <div class="mt-4">测算结果：</div>
        <div class="card mb-4">
          <div class="card-body bg-light">
            <div class="row">
              <div class="col">
                <div class="font-weight-bold">需求金额</div>
                <p class="calc-num text-warning">{{ calcNeedTotalStr }}</p>
              </div>
              <div class="col">
                <div class="font-weight-bold">授信金额</div>
                <p class="calc-num" :class="calcFundsTotal > 0 ? 'text-success' : 'text-danger'">
                  {{ calcFundsTotalStr }}
                </p>
              </div>
            </div>
          </div>
        </div>

        <span class="text-primary cursor-pointer" @click="indexesVisible = !indexesVisible">
          <span>详细信息</span>
          <i class="fa" :class="`fa-angle-${indexesVisible ? 'up' : 'down'}`"></i>
        </span>
        <transition name="el-zoom-in-top">
          <div v-show="indexesVisible" class="transition-box">
            <div v-for="(t, index) in calcTable" :key="index">
              <div class="font-weight-bold">{{ t.productName }}</div>
              <table class="table table-sm">
                <colgroup>
                  <col width="17%" />
                  <col width="45%" />
                  <col width="10%" />
                  <col width="10%" />
                  <col width="18%" />
                </colgroup>
                <thead>
                  <tr>
                    <th class="text-muted">产业链节点</th>
                    <th class="text-muted">指标</th>
                    <th class="text-muted">单价</th>
                    <th class="text-muted">系数</th>
                    <th class="text-right text-muted">需求合计</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in t.indexes" :key="index">
                    <td>{{ item.chainName }}</td>
                    <td>{{ item.indexName }}</td>
                    <td>{{ item.unitPrice }}</td>
                    <td>{{ item.coefficient }}</td>
                    <td class="text-right">{{ item.totalStr }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { getStoreByGoodsId, getProduct, getInfo } from '@/credit/views/province/goods/goodsStore'
import { add, mul, sub, stringFormatDot } from '@vimi/utils-tool'

export default {
  components: {},
  props: {
    visible: Boolean,
    goodsId: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      loading: false,
      indexesVisible: false,

      products: [],

      scalePeriod: 1,
      scaleUnit: '',
      scale: '',
      liabilities: '',

      calcStep: 0,
      calcTable: [],
      calcNeedTotal: 0,
      calcFundsTotal: 0,
      calcProfitTotal: 0,
    }
  },
  computed: {
    calcNeedTotalStr() {
      return stringFormatDot(this.calcNeedTotal)
    },
    calcFundsTotalStr() {
      return stringFormatDot(this.calcFundsTotal)
    },
    watchValue() {
      return this.visible + this.goodsId
    },
  },
  watch: {
    watchValue: {
      handler: function () {
        this.getGoodsStore()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
      this.scale = ''
      this.liabilities = ''
      this.calcStep = 0
    },
    async getGoodsStore() {
      if (!this.goodsId) return

      this.loading = true
      const [res, err] = await this.$utils.promise(
        Promise.all([
          getInfo(this.goodsId),
          getProduct(this.goodsId),
          getStoreByGoodsId(this.goodsId),
        ])
      )
      this.loading = false

      if (err) {
        return this.$message.error('获取数据失败')
      }

      const [info = {}, products = [], stores = []] = res
      const indexes = {}
      for (const index of stores) {
        if (!indexes[index.productId]) {
          indexes[index.productId] = [{ ...index }]
        } else {
          indexes[index.productId].push({ ...index })
        }
      }

      for (const product of products) {
        product.indexes = indexes[product.id] || []
      }

      this.scalePeriod = +(info.scalePeriod || '')
      this.scaleUnit = info.scaleUnit || ''
      this.products = products || []
    },
    // 测算
    handleClac() {
      const scale = +this.scale
      if (!scale) {
        return this.$message.error('请输入规模')
      }

      this.calcStep = 1
      this.calcNeedTotal = 0
      this.calcTable = []
      let calcFundsTotal = 0
      for (const product of this.products) {
        // 授信金额
        const productTotal = scale * product.unitScale * product.unitPrice * product.coefficient
        calcFundsTotal = add(calcFundsTotal, productTotal)

        const indexes = []
        for (const table of product.indexes) {
          if (!table.chainName) {
            continue
          }
          const period = table.isFixedInvest === 1 ? this.scalePeriod : 1
          const needTotal = mul(table.unitPrice, table.coefficient, scale, period)
          this.calcNeedTotal += needTotal
          indexes.push({
            ...table,
            total: needTotal,
            totalStr: needTotal.toFixed(2),
          })
        }

        this.calcTable.push({
          productName: product.productName,
          indexes,
        })
      }

      this.calcFundsTotal = sub(calcFundsTotal - +this.liabilities * 1e4)
    },
  },
}
</script>

<style lang="scss" scoped>
.calc-panel {
  max-width: 600px;
  min-height: 200px;
  transition: all 0.3s;
  transform: translate(0, 70px);
  &.show-result {
    transform: translate(0, 0);
  }
}
.calc-num {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 0;
}
</style>
